# -*- encoding: utf-8 -*-
import  os
from win32com import client
import os,datetime

def mkdir(path):
    folder = os.path.exists(path)
    if not folder:                   
        os.makedirs(path)            
        print("---  new folder【%s】...  ---"%(path))
        print("---  OK  ---")
    #else:
        #print("---  There is this folder!  ---")
        
def get_file_path(current_path,from_list_files,to_list_files):
    for dirName, subdirList, fileList in os.walk(current_path):
        for fname in fileList:
            if '.docx' in fname and 'template' not in fname and '$' not in fname:
                from_list_files.append(r'%s'%(dirName)+'\\'+fname)
                to_list_files.append(r'%s'%(dirName)+'\\pdf\\'+fname)
    
def doc2pdf(doc_name, pdf_name):
    """
    :word文件转pdf
    :param doc_name word文件名称
    :param pdf_name 转换后pdf文件名称
    """
    wordApp = client.DispatchEx("Word.Application")
    if os.path.exists(pdf_name):
        os.remove(pdf_name)
    worddoc = wordApp.Documents.Open(doc_name,ReadOnly = 1)
    worddoc.SaveAs(pdf_name, FileFormat = 17)
    worddoc.Close()
    wordApp.Quit()
    return pdf_name

def docx2pdf(from_file, to_file):
    input = r'%s'%(from_file)
    print(input);
    output = r'%s'%(to_file).replace(".docx", ".pdf");
    rc = doc2pdf(input, output)
    print(rc);
    if rc:
        print('转换成功')
    else:
        print('转换失败')

def extern_main(path):
    from_files = []
    to_files = []
    mkdir(path+"\\pdf")
    get_file_path(path,from_files,to_files)
    for i in range(0,len(from_files)):
        docx2pdf(from_files[i],to_files[i])
        
def main():
    from_files = []
    to_files = []
    root_dir = os.getcwd()
    mkdir(root_dir+"\\pdf")
    get_file_path(os.getcwd(),from_files,to_files)
    for i in range(0,len(from_files)):
        docx2pdf(from_files[i],to_files[i])
        
if __name__ == '__main__':
    main()